package com.cyz.springdemo.Controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyz.springdemo.config.ApiProperties;
import com.cyz.springdemo.model.AreaOil;
import com.cyz.springdemo.model.BaseResponse;
import com.cyz.springdemo.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springdemo
 * @description: 小程序接口控制器类
 * @author: wangjie
 * @create: 2019-07-25 15:28
 **/
@RestController
@RequestMapping(value = "/api")
public class APIController {


    @Autowired
    ApiProperties apiProperties;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private TaskExecutor taskExecutor;

    private final static Logger logger = LoggerFactory.getLogger(APIController.class);
    /**
     * 今日油价查询
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/todayoil",method = RequestMethod.GET)
    public BaseResponse todayoil(HttpServletRequest request) throws Exception {
        BaseResponse response = new BaseResponse();

        String prov = request.getParameter("prov");
        if (prov == null || prov.isEmpty()){
            response.setCode(1002);
            response.setMessage("省份不能为空");
            return response;
        }

        //获取缓存的数据
        Object strOil = redisTemplate.opsForValue().get(prov);
        //判断是否有缓存，如果没有则进行接口调用，返回数据，并添加到redis缓存中
        if (StringUtils.isEmpty(strOil)) {

            //获取接口的基本配置
            String host = apiProperties.getTodayoilHost();
            String path = apiProperties.getTodayoilPath();
            String method = apiProperties.getTodayoilMethod();
            String appcode = apiProperties.getTodayoilAppcode();

            //设置请求头
            Map<String,String> headers = new HashMap<String,String>();
            headers.put("Authorization","APPCODE " + appcode);

            Map<String, String> querys = new HashMap<String, String>();
            querys.put("prov", prov);
            HttpResponse httpResponse = HttpUtils.doGet(host, path, method, headers, querys);

            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(httpResponse.getEntity()));
            String resBody = jsonObject.getString("showapi_res_body");
            JSONObject resBodyObj = JSON.parseObject(resBody);

            JSONArray oilArray = JSONArray.parseArray(resBodyObj.getString("list"));
            AreaOil areaOil = oilArray.getObject(0,AreaOil.class);
            if (!StringUtils.isEmpty(areaOil)) {
                response.setMessage("查询成功");
                response.setData(areaOil);
                //缓存没有数据，新开一个线程进行缓存的存储
                taskExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        logger.info("2");
                        redisTemplate.opsForValue().set(areaOil.getProv(),areaOil);
                    }
                });

            } else {
                response.setCode(1001);
                response.setMessage("未查到相关地区的油价");
            }
        }else {
            response.setMessage("查询成功！");
            response.setData(strOil);
        }
        return response;
    }

    /*
     * 天气查询
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/weather",method = RequestMethod.POST)
    public Object areaWeather(HttpServletRequest request) throws Exception {

        String host = apiProperties.getWeatherHost();
        String path = apiProperties.getWeatherPath();
        String method = apiProperties.getWeatherMethod();
        String appcode = apiProperties.getWeatherAppcode();

        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Authorization","APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("area", request.getParameter("area"));
        querys.put("areaid", request.getParameter("areaid"));
        querys.put("need3HourForcast", request.getParameter("need3HourForcast"));
        querys.put("needAlarm", request.getParameter("needAlarm"));     //是否需要天气预警  需要1不需要0
        querys.put("needHourData", request.getParameter("needHourData"));//	是否需要每小时数据的累积数组
        querys.put("needIndex", request.getParameter("needIndex"));     //是否需要返回指数数据
        querys.put("needMoreDay", request.getParameter("needMoreDay")); //是否需要返回7天数据中的后4天

        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        return response.getEntity();
    }

}
